package com.achilles.learnresultreceiver;

import android.content.Intent;
import android.os.ResultReceiver;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button btn ;
    private Intent intent ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = (Button) findViewById(R.id.btn);

        intent = new Intent(MainActivity.this,CalcService.class);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent.putExtra("resultReceiver",mResultReceiver);
                startService(intent);
            }
        });
    }

    ResultReceiver mResultReceiver = new ResultReceiver(null){
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            super.onReceiveResult(resultCode, resultData);
            switch (resultCode){
                case CalcService.RESULTCODE_BEGIN:{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("AchillesL","calcService begin " + Thread.currentThread().getName());
                        }
                    });
                    break;
                }
                case CalcService.RESULTCODE_END:{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("AchillesL","calcService end " + Thread.currentThread().getName());
                        }
                    });
                    break;
                }
            }
        }
    };
}
